package com.tang.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.reggie.common.BaseContext;
import com.tang.reggie.dto.OrdersDto;
import com.tang.reggie.exception.CustomException;
import com.tang.reggie.mapper.OrdersMapper;
import com.tang.reggie.pojo.*;
import com.tang.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Override
    public void add(Orders orders) {
        //获取用户id
        Long currentId = BaseContext.getCurrentId();
        User user = userService.getById(currentId);
        //获取地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook==null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //获得订单id
        long orderId = IdWorker.getId();
        //获取购物车的总数量  使用之前已经写好的方法
        List<ShoppingCart> shoppingCartList = shoppingCartService.getAll(currentId);
        if (shoppingCartList==null||shoppingCartList.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }

        //初始化总金额
        AtomicInteger amount = new AtomicInteger(0);//确保原子性

        //计算总价格并且设置订单明细
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            BigDecimal amount1 = shoppingCart.getAmount();
            orderDetail.setAmount(amount1);
            //multiply乘  inValue 转为 int
            amount.addAndGet(amount1.multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //添加订单基本信息
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        //基本属性
        orders.setStatus(2);
        orders.setUserId(currentId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPhone(user.getPhone());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        //需处理地址
        orders.setAmount(new BigDecimal(amount.get()));//确保精度
        orders.setAddress((addressBook.getProvinceName()!=null?addressBook.getProvinceName():"")+
                (addressBook.getCityName()!=null?addressBook.getCityName():"")+
                (addressBook.getDistrictName()!=null?addressBook.getDistrictName():"")+
                (addressBook.getDetail()!=null?addressBook.getDetail():"")
                );
        //添加订单
        super.save(orders);

        //添加订单明细
        orderDetailService.saveBatch(orderDetailList);

        //清空购物车数据
        shoppingCartService.clean(currentId);
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrdersDto> getPage(int page, int pageSize) {
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>(page,pageSize);
        //查询出订单信息
        //用户id
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(currentId!=null,Orders::getUserId,currentId);
        //添加排序条件
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        //查询出订单数据
        super.page(ordersPage, ordersLambdaQueryWrapper);

        //将查询出来的分页数据如总数，提交给ordersPage，排除掉records订单明细
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");

        //添加订单明细信息
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            Long ordersId = Long.parseLong(orders.getNumber());
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, ordersId);
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());

        //将查出来的订单明细添加到ordersDtoPage类中
        ordersDtoPage.setRecords(ordersDtoList);

        return ordersDtoPage;
    }

    @Override
    public Page<Orders> getAll(int page, int pageSize, Long number, LocalDateTime beginTime, LocalDateTime endTime) {
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.like(number!=null,Orders::getNumber,number);
        ordersLambdaQueryWrapper.between(beginTime!=null,Orders::getOrderTime,beginTime,endTime);
        Page<Orders> ordersPage1 = super.page(ordersPage, ordersLambdaQueryWrapper);

        return ordersPage1;
    }

    @Override
    public void again(Orders orders) {
        //根据订单id添加订单的信息到购物车中
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
        //select * from order_detail where order_id = ?
        List<OrderDetail> orderDetails = orderDetailService.list(orderDetailLambdaQueryWrapper);

        orderDetails.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);

            shoppingCart.setId(null);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartService.add(shoppingCart);
            return shoppingCart;
        }).collect(Collectors.toList());
    }
}
